//
//  APIError.swift
//  Link
//
//  Created by melvyn on 2018/8/21.
//  Copyright © 2018 NEET. All rights reserved.
//

import Foundation

public enum APIError: Error {
    public enum AuthenticatedFailedReason {
        case invalidToken
        case unauthorized
    }

    public enum SocketFailedReason {
        case unauthorized
        case disconnected
    }
  
    case dataUploadFailed
    case autheticatedFailed(reason: AuthenticatedFailedReason)
    case socketFailed(reason: SocketFailedReason)
    case undefine
}

extension APIError {
    var localizedDescription: String {
        switch self {
        case .dataUploadFailed:
            return "Data upload failed"
        case .autheticatedFailed(reason: let reason):
            return reason.localizedDescription
        case .socketFailed(reason: let reason):
            return reason.localizedDescription
        case .undefine:
            return ""
        }
    }
}

extension APIError.AuthenticatedFailedReason {
    var localizedDescription: String {
        switch self {
        case .invalidToken:
            return "Token is expired"
        case .unauthorized:
            return "Username or password is incorrect"
        }
    }
}

extension APIError.SocketFailedReason {
    var localizedDescription: String {
        switch self {
        case .unauthorized:
            return "User not authorized or token is expired"
        case .disconnected:
            return "Socket not connected"
        }
    }
}

extension APIError: LocalizedError {
    public var errorDescription: String? {
        switch self {
        case .dataUploadFailed, .undefine:
            return localizedDescription
        case .autheticatedFailed(reason: let reason):
            return reason.localizedDescription
        case .socketFailed(reason: let reason):
            return reason.localizedDescription
        }
    }
}
